﻿window.User = Backbone.Model.extend({
    defaults: {
        id: 1,
        MemLoginID: "",
        Pwd: ""
    }
});

window.AutoLoginModel = User.extend({
    urlRoot: 'api/account/setauth/',
    url: function () {
        return this.urlRoot + pageView.getCookieValue('uid');
    }
});

window.LoginModel = User.extend({
    urlRoot: 'api/account/login/',
    url: function () {
        return this.urlRoot;
    }
});

window.LoginView = Backbone.View.extend({
    el: "#jqt",

    events: {
        'click #loginBtn': 'authencation'
    },

    initialize: function () {
        this.model = new LoginModel();
        this.template = $('#LoginTemplate').html();
    },

    render: function () {
        var partial = { header: $('#HeaderTemplate').html(), footer: $('#FooterTemplate').html(), innerFooter: $('#InnerFooterTemplate').html() };
        var data = { title: "登录ShopNum1", btnListR: [{ name: 'home'}] };

        this.$el.append(Mustache.render(this.template, data, partial));

        $('#UserName').val(localStorage.getItem('username'));

        //this.checkCookieTimeout();

        return this;
    },

    checkCookieTimeout: function () {
        if (!pageView.getCookieValue('uid')) {
            $('#loginError').html('session超时,请重新登录');
        }
    },

    validation: function () {
        if (this.$el.find('#UserName').val() === "") {
            $('#loginError').html('用户名不能为空');
            return false;
        }
        if (this.$el.find('#Password').val() === "") {
            $('#loginError').html('密码不能为空');
            return false;
        } else {
            //this.encryptPassword(this.$el.find('#Password').val());
        }
        return true;
    },

    checkUserExisted: function () {
        var username = $('#UserName').val();
        var flag = true;
        $.ajax({
            url: 'api/account/userexist/' + username,
            dataType: 'json',
            async: false,
            success: function (res) {
                if (res != null && res == false) {
                    $('#loginError').text('用户名不存在！');
                    flag = false;
                }
            }
        });
        return flag;
    },

    encryptPassword: function (value) {
        $('#Password').val(
            $.md5(value)
        );
    },

    authencation: function () {
        var that = this;
        if (this.validation()) {
            if (this.checkUserExisted()) {
                that.model.set('MemLoginID', this.$el.find('#UserName').val());
                that.model.set('Pwd', this.$el.find('#Password').val());
                that.model.set('RememberMe', $('input#remember')[0].checked);
                that.model.save('id', this.model.id, {
                    success: function (model, res) {
                        if (res != null && res == 200) {
                            that.model.set(res);
                            //localStorage.setItem('loginid', that.model.get('MemLoginID'));
                            var loginfrom = localStorage.getItem('loginfrom');
                            if (loginfrom) {
                                LoginView.loginAfterAction(loginfrom).call();
                            }
                            else pageView.goTo('MyUserInfo');
                        } else if (res != null && res == 404) {
                            $('#loginError').html('密码错误！请重新登录');
                        }
                    }
                });
            }
        }
    }
}, {
    loginAfterAction: function (key) {
        var action = function () { };
        switch (key) {
            case 'fetchCart': action = function () {
                pageView.goTo('MyCart');
            }; break;
            case 'addCart': action = function () {
                var product = JSON.parse(localStorage.getItem('productDetail'));
                MyCartView.addToCarts(product['productid'], product['price'], 1, function () {
                    pageView.goTo('MyCart');
                });
            }; break;
            case 'myCollect': action = function () {
                pageView.goTo('MyCollect');
            }; break;
            case 'myMessage': action = function () {
                pageView.goTo('MyMessage');
            }; break;
            case 'myOrder': action = function () {
                pageView.goTo('MyOrder');
            }; break;
            case 'addCollect': action = function () {
                MyCollectView.addToMyCollect(function () {
                    pageView.goTo('MyCollect');
                });

            }; break;
        }
        return action;
    }
});